import { Component, OnInit, Injector, Input, ViewChild } from '@angular/core';
import { DataDictionary, DataTreeNodeInterface } from 'entities';
import { DataDictionaryService } from 'services';
import { AppComponentBase } from '@shared/component-base/app-component-base';
import { PagedResultDto } from '@shared/component-base/paged-listing-component-base';
import { CreateOrUpdateDatadictionaryComponent } from '../create-or-update-datadictionary/create-or-update-datadictionary.component';
import { NzModalRef, NzModalService } from 'ng-zorro-antd';
import { DataTreeSelectComponent } from '@app/components/data-tree-select/data-tree-select.component';

@Component({
    selector: 'app-data-list',
    templateUrl: './data-list.component.html',
    styles: [],
    providers: [DataDictionaryService],
})
export class DataListComponent extends AppComponentBase
    implements OnInit {
    @ViewChild("dataTree") dataTree: DataTreeSelectComponent;
    _group: any;
    @Input()
    set group(group: any) {
        //alert(JSON.stringify(group))
        if (!group) {
            return;
        }
        if (!this._group || this._group.id != group.id) {
            this._group = group;
            this.refresh();
        }
    }
    get group(): any { return this._group; }

    search: any = {};
    tableLoading = false;
    dataDictionary: DataDictionary = new DataDictionary();
    isVisible: boolean = false;

    constructor(
        injector: Injector,
        private dataDictionaryService: DataDictionaryService,
        private modal: NzModalService
    ) {
        super(injector);
    }

    ngOnInit() {

    }

    //查询
    getDataDictionarys() {
        if (!this.group) {
            return;
        }
        this.tableLoading = true;
        let params: any = {};
        params.SkipCount = this.query.skipCount();
        params.MaxResultCount = 100;//this.query.pageSize;
        params.Value = this.search.text;
        params.Group = this.group.id;
        params.sorting = 'Group';
        this.dataDictionaryService
            .getAll(params)
            .subscribe((result: PagedResultDto) => {
                this.tableLoading = false;
                this.query.dataList = result.items;
                this.query.total = result.totalCount;
                if (this.group.mode == 2) {
                    this.query.dataList.forEach(item => {
                        this.expandDataCache[item.id] = this.convertTreeToList(item);
                    });
                }
            });
    }

    //删除
    delete(entity: DataDictionary) {
        this.message.confirm(
            "是否确认删除数据:'" + entity.value + "'?",
            '信息确认',
            (result: boolean) => {
                if (result) {
                    this.dataDictionaryService.delete(entity.id).subscribe(() => {
                        this.notify.success('删除成功！');
                        this.getDataDictionarys();
                    });
                }
            },
        );
    }

    //编辑
    editDing(item: DataDictionary) {
        let parentData;
        if (item.parentId != 0) {
            parentData = this.query.dataList.find(d => d.id == item.parentId);
        }

        let dataCodes = [];
        if (this.query.dataList) {
            this.query.dataList.forEach((data) => {
                if (item.code != data.code) {
                    dataCodes.push(data.code);
                }
            })
        }

        this.modalHelper
            .open(
                CreateOrUpdateDatadictionaryComponent,
                {
                    id: item.id,
                    group: this.group,
                    parent: parentData,
                    codes: dataCodes
                },
                'md',
                {
                    nzMask: true,
                },
            )
            .subscribe(isSave => {
                if (isSave) {
                    this.getDataDictionarys();
                }
            });
    }

    //添加子项
    addSubset(item: DataDictionary) {
        let dataCodes = [];
        if (this.query.dataList) {
            this.query.dataList.forEach((data) => {
                dataCodes.push(data.code);
            })
        }
        this.modalHelper
            .open(
                CreateOrUpdateDatadictionaryComponent,
                {
                    parent: item,
                    group: this.group,
                    codes: dataCodes
                },
                'md',
                {
                    nzMask: true,
                },
            )
            .subscribe(isSave => {
                if (isSave) {
                    this.getDataDictionarys();
                }
            });
    }

    //创建
    create() {
        let dataCodes = [];
        if (this.query.dataList) {
            this.query.dataList.forEach((data) => {
                dataCodes.push(data.code);
            })
        }
        this.modalHelper
            .open(
                CreateOrUpdateDatadictionaryComponent,
                { group: this.group, codes: dataCodes },
                'md',
                {
                    nzMask: true,
                },
            )
            .subscribe(isSave => {
                if (isSave) {
                    this.getDataDictionarys();
                }
            });
    }

    //重置
    refresh() {
        this.search = {};
        this.query.pageIndex = 1;
        this.getDataDictionarys();
    }

    //树
    expandDataCache = {};
    collapse(array: DataTreeNodeInterface[], data: DataTreeNodeInterface, $event: boolean): void {
        if ($event === false) {
            if (data.children) {
                data.children.forEach(d => {
                    const target = array.find(a => a.id === d.id);
                    target.expand = false;
                    this.collapse(array, target, false);
                });
            } else {
                return;
            }
        }
    }

    convertTreeToList(root: object): DataTreeNodeInterface[] {
        const stack = [];
        const array = [];
        const hashMap = {};
        stack.push({ ...root, level: 0, expand: false });

        while (stack.length !== 0) {
            const node = stack.pop();
            this.visitNode(node, hashMap, array);
            if (node.children) {
                for (let i = node.children.length - 1; i >= 0; i--) {
                    stack.push({ ...node.children[i], level: node.level + 1, expand: false, parent: node });
                }
            }
        }

        return array;
    }

    visitNode(node: DataTreeNodeInterface, hashMap: object, array: DataTreeNodeInterface[]): void {
        if (!hashMap[node.id]) {
            hashMap[node.id] = true;
            array.push(node);
        }
    }

    confirmModal?: NzModalRef;

    //升级
    upgrade(item: DataDictionary) {
        this.confirmModal = this.modal.confirm({
            nzTitle: '升级确认',
            nzContent: '确定要升级[' + item.desc + ']吗？',
            nzOnOk: () => {
                this.dataDictionaryService.treeUpgrade(item.id).subscribe(() => {
                    this.getDataDictionarys();
                });
            }
        });

    }

    //降级
    downgrade(item: DataDictionary) {
        this.confirmModal = this.modal.confirm({
            nzTitle: '降级确认',
            nzContent: '确定要降级[' + item.desc + ']吗？',
            nzOnOk: () => {
                this.dataDictionaryService.treeDowngrade(item.id).subscribe(() => {
                    this.getDataDictionarys();
                });
            }
        });
    }

    transferItem: DataDictionary;
    transferCode: string;
    isTransferLoading: boolean;

    //转移
    transfer(item: DataDictionary) {
        this.transferItem = item;
        const pnode = this.query.dataList.find(d => d.id == item.parentId);
        if (pnode) {
            this.transferCode = pnode.code;
        } else {
            this.transferCode = item.code;
        }
        this.isVisible = true;
    }

    handleOk(): void {
        this.isTransferLoading = true;
        const pnode = this.query.dataList.find(d => d.code == this.transferCode);
        if (!pnode) {
            this.notify.info('请选择转移节点');
            return;
        }
        this.dataDictionaryService.treeTransfer(this.transferItem.id, pnode.id).finally(() => {
            this.isTransferLoading = false;
        }).subscribe(() => {
            this.getDataDictionarys();
            this.dataTree.getTreeNode();
            this.isVisible = false;
        });
    }

    handleCancel(): void {
        this.isVisible = false;
    }

}
